﻿layui.extend({
    timemsg: 'modules/timemsg'
}).define(['jquery', 'timemsg', 'form', 'element'], function (exports) {
    var $ = layui.jquery
        , timemsg = layui.timemsg
        , form = layui.form
        , element = layui.element
    var obj = {
        custom: function (active, options) {
            /**
             * 方法说明 按钮伸缩引用 Form 自定义
             * @param {Str} active Form Header 按钮运行代码存在页面内引用
             * @param {Object} options 配置项
            */
            initOption = {
                nameFlag: 'name',   //输入框标识字段
                itemClosestParentClass: 'layui-row', //item 块最外层的直接父元素 class 标识
                itemClass: 'layui-form-item',    //包裹 item 的最内层 class 标识
                itemClosest: '.layui-row > .layui-col-xs12',    //包裹 item 的最外层选择器
                //PointIndex: 3   //拖动时 elementsFromPoint 选取的 index
                headerRWSelector: [' > .layui-form-checkbox', ' > text'],
                isIframeSon: false      // 是否是包裹在父窗口中。
            }
            $.extend(initOption, options || {})
            var _this = this, $form = $('form.layui-form')
            var $form_card, $headerl, $btnGroup, $btnGroup1
            if (initOption.isTabFormView) {    //tab 选项卡
                var $tabCard = $('.forceForm-tabCard')
                $form_card = $form.closest('.layui-tab-item:not(.layui-hide)')
                $headerl = $tabCard.find('.layui-tab-title')
                $btnGroup = $tabCard.find('.my-tab-title .header-btn-group')
                $btnGroup1 = $btnGroup
            } else if (initOption.isCollaFormView) {    //折叠面板
                var $collaCard = $('.forceForm-collaCard')
                $form_card = $form.closest('.layui-card:not(.layui-hide)')
                $headerl = $collaCard.find('.layui-colla-title')
                $btnGroup = $headerl.find('.header-btn-group')
                $btnGroup1 = $btnGroup
            } else {
                $form_card = $form.closest('.layui-card:not(.layui-hide)')
                $headerl = $form_card.last().find('.layui-card-header')
                $btnGroup = $form_card.find('.header-btn-group')
                $btnGroup1 = $headerl.find('.header-btn-group')
            }
            if ($btnGroup1.length == 0) { return; }
            //if ($form_card.last().hasClass('tab_form_card') && $form.closest('.layui-card').length == 1) { return; }    //form循环未结束

            var childBtnGW = {}, isFirst = true, childBtnGroupName = null;
            $(window).resize(debounce(headerBtnFlex, null, 100)) //窗口变化
            headerBtnFlex()
            activeBind()

            function activeBind($form_card) {
                //绑定按钮事件
                $btnGroup.find('[data-type]').off('mouseup').on('mouseup', function () {
                    var type = $(this).data('type');
                    if (active) {
                        active[type] ? active[type].call(this, arguments) : '';
                    }
                    if (layui.active) {
                        layui.active[type] ? layui.active[type].call(this, arguments) : '';
                    }
                });

                if (initOption.isCollaFormView) {
                    //折叠面板
                    $btnGroup.find('[data-type]').on('click', function (e) {
                        //阻止冒泡
                        e.stopPropagation()
                    })
                }
            }
            function headerBtnFlex() {
                var $btnM = $btnGroup.find('.header-option > .btn_more'), $optionBtn = $btnGroup.find('.btn-option > .layui-btn'), surSum, isMobile = false

                var reBtn = $btnGroup1.find(' > .layui-btn'), btnvSum = $btnGroup1.find(' > .layui-btn:visible').length,
                    hOtherW = 0;
                if ($.type(initOption.headerRWSelector) === 'array') {
                    initOption.headerRWSelector.forEach(function (item) {
                        $headerl.find(item).each(function (i, elem) {
                            hOtherW += $(this).outerWidth(true)
                        })
                    })
                }
                var hBtnWidth = $headerl.width() - hOtherW, optionWs = {}
                if (/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)) {
                    // 移动端
                    surSum = 0
                    isMobile = true

                } else {
                    getSurSum()
                }
                function getSurSum(cardIndex) {
                    if (!cardIndex) {   //有索引为刷新，不能重置 optionWs 
                        optionWs = { '99': {} }, optionWs['99'].optionW = 0
                    }
                    $form_card.each(function () {
                        var $thisCard = $(this), index = $thisCard.index()
                        if (!!cardIndex && cardIndex != index) { return; }
                        optionWs[index] = {}

                        var $thisGroupOption;
                        if (initOption.isTabFormView || initOption.isCollaFormView) $thisGroupOption = $btnGroup.find('.option:visible')   //为 tab form 循环 则为 $tabCard groupOption
                        else $thisGroupOption = $thisCard.find('.header-btn-group .option:visible')

                        $thisGroupOption.each(function () {
                            optionWs[index].optionW = (optionWs[index].optionW || 0) + $(this).outerWidth(true)
                            optionWs['99'].optionW = (optionWs[index].optionW > optionWs['99'].optionW) ? optionWs[index].optionW : optionWs['99'].optionW
                        })
                        optionWs[index].surSum = ~~((hBtnWidth - optionWs[index].optionW - 25) / (reBtn.eq(0).outerWidth(true) || 30))
                        surSum = optionWs['99'].surSum = ~~((hBtnWidth - optionWs['99'].optionW - 25) / (reBtn.eq(0).outerWidth(true) || 30))
                        !(optionWs[index].surSum < 0) || (optionWs[index].surSum = 0)   //防止出现负数
                    })
                    //surSum != 0 || (surSum = surSum + 1)    //保留 1 个
                }
                //识别显示隐藏 moreBtn
                if (isFirst) {
                    if ($btnGroup.find('.header-option .layui-nav-child *').length == 0 || isMobile) {
                        $btnM.css('display', 'none')
                    } else if (!isMobile) {
                        $btnM.css('display', 'inline-block')
                    }
                    //绑定按钮事件
                    activeBind($form_card)
                    //按钮组
                    $optionBtn.on('mousedown', function () {
                        var $this = $(this), $btnG = $this.siblings('.isShow'), isAct = $this.hasClass('active')
                        if ($btnG.length > 0) {
                            if (isAct) {
                                $btnG.css('display', 'none')
                            } else {
                                $btnG.css('display', 'inline-block')
                                childBtnGW[$this.attr('title')] = $btnG.outerWidth(true)
                                childBtnGroupName = $this.attr('title')
                                headerBtnFlex()
                            }
                        } else {
                            var $thisNavChildOp = $this.parent().siblings('.header-option').find('[alt="' + $this.attr('title') + '"]'), $navChild = $thisNavChildOp.parent()
                            if (isAct) {
                                $thisNavChildOp.css('display', 'none')
                                $thisNavChildOp.removeClass('isShow')
                                    ; ($navChild.children('.isShow').length != 0 || $navChild.children(':not([option])').length != 0) || $navChild.siblings('.layui-btn').hide()
                            } else {
                                $thisNavChildOp.css('display', 'block')
                                $thisNavChildOp.addClass('isShow')
                                $navChild.siblings('.layui-btn').show()
                            }
                        }
                        if (isAct) {
                            $this.removeClass('active')
                        } else {
                            $this.addClass('active')
                        }
                    })
                    isFirst = false
                }
                //识别显示隐藏 moreIcon
                var $moreIcon = $btnGroup.find('.header-option > .layui-icon-more')
                if (isMobile) {
                    $moreIcon.css('display', 'inline-block')
                    $optionBtn.css('display', 'none')
                } else {
                    $optionBtn.css('display', 'inline-block')
                    $moreIcon.css('display', 'none')
                }

                //没有需要隐藏显示的选项时直接跳出
                if (((btnvSum < surSum || btnvSum == surSum) && reBtn.length == btnvSum && $btnGroup.find('.header-option .layui-nav-child div[option]').length == 0) && surSum != 0) { childBtnGroupName = null; return; }

                $form_card.each(function () {
                    var index = $(this).index(), thisSurSum = isMobile ? surSum : optionWs[index].surSum
                    var $group;
                    if (initOption.isTabFormView || initOption.isCollaFormView) {
                        $group = $btnGroup   //为 tab form 循环 则为 $btnGroup1
                    } else {
                        $group = $(this).find('.layui-card-header .header-btn-group')
                    }

                    var $optionChild = $group.find('.header-option .layui-nav-child')
                    //显示的Btn大于预留下来的数量、空间不够点击按钮组时（有顶层按钮、无顶层按钮）进入
                    if (btnvSum > thisSurSum || (btnvSum == 0 && thisSurSum == 0 && reBtn.length != 0 && childBtnGroupName) || (reBtn.length == 0 && !(thisSurSum > 0)) || isMobile) {
                        //隐藏btn
                        //if (btnvSum == 1 && !isMobile) { return; }  //保留1个

                        var $btng, $optionM = $('<div><a></a></div>')
                        //隐藏子按钮组
                        //var childBtnGroup = $group.find('.isShow') //同步隐藏child-btn-group
                        var childBtnGroup = isMobile ? $group.find('.child-btn-group') : $group.find('.child-btn-group:visible')
                        childBtnGroup.each(function (i) {
                            //if (childBtnGroupName != $(this).siblings('.layui-btn').attr('title')) { return; }    //同步隐藏child-btn-group
                            var $this = $(this), childOptionGroup = $('<div/>', { 'class': 'isShow', 'alt': $this.siblings('.layui-btn').attr('title'), 'option': '' })
                            $this.hide()
                            $this.children('.layui-btn').each(function () {
                                var childOption = addHeaderOp.call(this, true)
                                if (!childOption) { return; }
                                childOption.appendTo(childOptionGroup)
                            })
                            if (childOptionGroup.find('div').length == 0) { return; }
                            childOptionGroup.append('<hr/>')
                            childOptionGroup.prependTo($optionChild)
                            $this.removeClass('isShow')
                            if (btnvSum == 0 || isMobile) { return; }
                            getSurSum(index) //更新保留按钮个数
                            thisSurSum = isMobile ? surSum : optionWs[index].surSum
                            if (btnvSum < thisSurSum || btnvSum == thisSurSum) { return false; }
                        })
                        if (btnvSum < thisSurSum || btnvSum == thisSurSum) { return; }

                        if (isMobile) {
                            $btng = $group.find(' > .layui-btn')
                        } else {
                            $btng = thisSurSum == 0 ? $group.find(' > .layui-btn') : $group.find(' > .layui-btn:gt(' + ~~(thisSurSum - 1) + ')')
                        }
                        $btng.css('animation', 'rfade 0.2s ease')
                        setTimeout(function () {
                            $btng.css({ 'display': 'none', 'animation': 'rcome 0.2s ease' })
                        }, 80)
                        $($btng.toArray().reverse()).each(addHeaderOp)
                        function addHeaderOp(isBtnGroup) {
                            var $this = $(this)
                            if ($optionChild.find('div[alt="' + $this.attr('title') + '"]').length > 0) { return; }
                            var $optionC = $optionM.clone()
                            $optionC.attr({ 'data-type': $this.attr('data-type'), 'alt': $this.attr('title') })
                            $optionC.find('a').text($this.attr('title'))
                            if (isBtnGroup === true) { return $optionC; }
                            $optionC.appendTo($optionChild)
                        }
                        //（显示的Btn小于预留下来的数量、）非移动端
                    } else if (!isMobile && btnvSum < thisSurSum) {
                        //显示 btn 
                        if (btnvSum < reBtn.length) {
                            var $btnl = $group.find(' > .layui-btn:lt(' + ~~(thisSurSum) + ')')
                            $btnl.css('display', 'inline-block')
                            $btnl.each(function () {
                                $optionChild.find('div[alt="' + $(this).attr('title') + '"]').remove()
                            })
                        }

                        var overSum = thisSurSum - reBtn.length
                        if (overSum < 1) { return; }
                        $($optionChild.find('div[option]').toArray().reverse()).each(function () {
                            var optionTitle = $(this).attr('alt'), currentBtnGSum = childBtnGW[optionTitle] / (reBtn.eq(0).outerWidth(true) || 30)
                            if (currentBtnGSum > overSum) { return false; }
                            var $childBtn = $group.find('.layui-btn[title="' + optionTitle + '"]'), $childGroup = $childBtn.siblings('.child-btn-group')
                            $childGroup.addClass('isShow')
                            if ($childBtn.hasClass('active')) {
                                $childGroup.css('display', 'inline-block')
                            }
                            overSum = overSum - currentBtnGSum
                            $(this).remove()

                        })
                    }
                })
                childBtnGroupName = null
                //绑定按钮事件
                activeBind($form_card)
                //识别隐藏 moreBtn
                $btnM.each(function () {
                    var $navChild = $(this).siblings('.layui-nav-child')
                    if (($navChild.children('.isShow').length == 0 && $navChild.children(':not([option])').length == 0) || isMobile) {
                        $btnM.css('display', 'none')
                    } else if (!isMobile) {
                        $btnM.css('display', 'inline-block')
                    }
                })
            }

            if ($form.length === 0) { return; }
            _this.formCus()  //运行form拖动

            if (initOption.isIframeSon) {
                select2Height() //防止页内高度不够select2显示
                laydateHeight() //防止页内高度不够lay-date显示
            }
        },
        formCus: function () {
            var $form = $('form.layui-form'), formLocal = {};
            if ($form.length == 0) { return; }
            if (!$(frameElement).parent().hasClass('layadmin-tabsbody-item')) { timemsg = parent.layui.timemsg }
            // $form.each(function () {
            //     var $this = $(this), filter = $this.attr('formClass') || $this.attr('lay-filter'), billType = location.pathname + ':' + filter
            //     AccountDefaultLoad(filter, billType, $this, layui)  // 默认值加载
            //     formLocal[filter] = deepParse(localStorage.getItem(billType))   //获取当前 form 自定义
            //     if (Object.keys(formLocal[filter]).length == 0) { return; }
            //     var newform = $this.find('.' + initOption.itemClosestParentClass + ':first > div').toArray().sort(function (a, b) {
            //         //按自定义重新排序
            //         return formLocal[filter][$(a).find('[' + initOption.nameFlag + ']').attr(initOption.nameFlag)] - formLocal[filter][$(b).find('[' + initOption.nameFlag + ']').attr(initOption.nameFlag)]
            //     })
            //     var newrow = $('<div/>', { class: initOption.itemClosestParentClass }).append(newform)
            //     if (!!formLocal[filter]['hide']) {
            //         //按自定义隐藏显示
            //         $.each(formLocal[filter]['hide'], function (i, item) {
            //             newrow.find('[' + initOption.nameFlag + '="' + item + '"]').closest(initOption.itemClosest).addClass('layui-hide')
            //         })
            //         newrow.find('.layui-hide [' + initOption.nameFlag + ']').each(function () {
            //             if (formLocal[filter]['hide'].indexOf($(this).attr(initOption.nameFlag)) == -1) {
            //                 $(this).closest(initOption.itemClosest).removeClass('layui-hide')
            //             }
            //         })
            //     }
            //     $this.find('.' + initOption.itemClosestParentClass + ':first').replaceWith(newrow)    //以 layui-row 为容器替换所有 input
            //     //$(this).find('.layui-row').html(newform)  //select2 死掉
            // })
            enterTab()

            function elementsFromPoint(X, Y) {
                if (!!document.elementsFromPoint) {
                    return document.elementsFromPoint(X, Y)
                } else {
                    return document.msElementsFromPoint(X, Y)
                }
            }
            //var jqSelector = 'div:not(.layui-hide) > div.layui-form-item .layui-input-inline [name]:not(select.select2-hidden-accessible, .layui-disabled, [disabled], :hidden), div:not(.layui-hide) > div.layui-form-item .layui-input-inline span.select2:not(.select2-container--disabled) span.select2-selection';
            function doDrag($lable) {
                var isStart = false, isDraging = false, timeout = null;

                $lable.css('cursor', 'move')
                    .on('mousedown', function (e) {
                        //var $item = $(this).parent().parent(),
                        var $item = $(this).closest(initOption.itemClosest),     //移动元素，原元素
                            itemP = $item.position(),
                            disX = e.clientX - itemP.left,
                            disY = e.clientY - itemP.top,
                            PointIndex = $(this).parents(initOption.itemClosest + ' *').length + 2,
                            inputW = $(this).next().width(),
                            $cloneItem = $item.clone().css('visibility', 'hidden')      //占位元素

                        isStart = true;
                        e.preventDefault(); //阻止默认事件
                        // 移动事件
                        $form.on('mousemove', function (e) {
                            if (!isStart) { return; }
                            if (!isDraging) {
                                $item.addClass('Draging')
                                $item.after($cloneItem);
                            }
                            isDraging = true
                            $item.css({ 'left': e.clientX - disX, 'top': e.clientY - disY })

                            clearTimeout(timeout); // 保证用户输入完之后只有一个setTimeout
                            timeout = setTimeout(function () {
                                var $cruxE = $(elementsFromPoint(e.clientX, e.clientY)[PointIndex])
                                if ($cruxE.hasClass(initOption.itemClass)) {
                                    var $posE = $(elementsFromPoint(e.clientX + inputW / 2, e.clientY)[4]).closest(initOption.itemClosest)
                                    if ($posE.length > 0) {
                                        $posE.before($cloneItem)    //使用 $cloneItem 占位
                                    }
                                } else if ($cruxE[0].tagName == 'LABEL') {
                                    $cruxE.closest(initOption.itemClosest).before($cloneItem)    //使用 $cloneItem 占位
                                } else if ($cruxE[0].tagName == 'INPUT' || $cruxE[0].tagName == 'SPAN' || $cruxE[0].tagName == 'TEXTAREA') {
                                    $cruxE.closest(initOption.itemClosest).after($cloneItem)    //使用 $cloneItem 占位
                                }
                            }, 15);

                        }).on('mouseup', function (e) {
                            //松开鼠标
                            $(this).off('mousemove').off('mouseup')
                            if (!isStart) { return; }
                            isStart = false
                            if (isDraging && $cloneItem.parent().length > 0) {
                                $cloneItem.replaceWith($item)   //将占位元素替换为原元素
                            }
                            $cloneItem.remove()
                            $item.removeClass('Draging').css({ 'left': '', 'top': '' })
                            isDraging = false

                            var filter = $(this).attr('formClass') || $(this).attr('lay-filter')
                            $(this).find('.' + initOption.itemClass).find('[' + initOption.nameFlag + ']').each(function (i) {
                                formLocal[filter][$(this).attr(initOption.nameFlag)] = i
                            })
                            if (!!layui.enterTab) {
                                layui.enterTab.$inputs = $form.find(layui.enterTab.jqSelector); // 更新表单中的所有可用输入框，用于更新enterTab
                            }
                            localStorage.setItem(location.pathname + ':' + filter, deepStringify(formLocal[filter]))  //保存本地
                        })
                    })
            }
            // getAccountId()  //确保top.layui.AccountId存在
            layui.active || (layui.active = {})
            //切换自定义 form 启动关闭
            layui.active.FormCustom = function () {
                //headerBtnAuto后的最终状态
                var $lable,
                    $tabCard = $(this).closest('.forceForm-tabCard'),
                    $collaCard = $(this).closest('.forceForm-collaCard')
                if ($tabCard.length > 0 && $collaCard.length === 0) {
                    var $checkElem = $tabCard.find(':not(.forceForm-card) [name="forceFormCheck"]:checked').eq(0),
                        $form = $checkElem.closest('.forceForm-item').find('form')
                    $lable = $form.find('.layui-form-label')
                } else if ($collaCard.length > 0 && $tabCard.length === 0) {
                    var $checkElem = $collaCard.find(':not(.forceForm-card) [name="forceFormCheck"]:first'),
                        $form = $checkElem.closest('.forceForm-item').find('form')
                    $lable = $form.find('.layui-form-label')
                } else {
                    $lable = $(this).closest('.layui-card-header').siblings('.layui-card-body').find('form').find('.layui-form-label')
                }
                if ($(this).hasClass('active')) {
                    doDrag($lable)
                } else {
                    $lable.css('cursor', 'default').off('mousedown')
                }
            }
            //上传缓存
            // layui.active.uploadFormLocal = function () {
            //     var $form = return$Form($(this))
            //     var filter = $form.attr('formClass') || $form.attr('lay-filter'),
            //         FormLocalUrl = location.pathname + ':' + filter,
            //         FormLocal = localStorage.getItem(FormLocalUrl)
            //     if (!FormLocal) {
            //         timemsg.open('本地缓存为空，上传个性化设置失败！')
            //         return;
            //     }

            //     $.ajax({
            //         url: '/api/UserConfig',
            //         type: 'post',
            //         data: {
            //             AccountID: top.layui.AccountId,
            //             ConfigKey: FormLocalUrl,
            //             ConfigValue: FormLocal
            //         },
            //         success: function (d) {
            //             timemsg.open('保存个性化设置' + d.message)
            //             if (!!$form.attr('formClass')) {
            //                 window.location.reload()
            //                 return;
            //             }
            //         },
            //         error: function () {
            //             timemsg.open('上传个性化设置失败！')
            //         }
            //     })
            // }
            //下载缓存
            // layui.active.downFormLocal = function () {
            //     var $form = return$Form($(this))
            //     var filter = $form.attr('formClass') || $form.attr('lay-filter'),
            //         FormLocalUrl = location.pathname + ':' + filter

            //     $.ajax({
            //         url: '/api/UserConfig',
            //         type: 'get',
            //         data: {
            //             AccountID: top.layui.AccountId,
            //             ConfigKey: FormLocalUrl
            //         },
            //         success: function (d) {
            //             timemsg.open('下载个性化设置' + d.message)
            //             if (!!layui.enterTab) {
            //                 layui.enterTab.$inputs = $form.find(layui.enterTab.jqSelector); // 更新表单中的所有可用输入框，用于更新enterTab
            //             }
            //             localStorage.setItem(FormLocalUrl, d.data.ConfigValue)

            //             if (!!$form.attr('formClass')) {
            //                 window.location.reload()
            //                 return;
            //             }
            //             var FormLocal = formLocal[filter] = deepParse(d.data.ConfigValue)
            //             //重新渲染
            //             var newform = $form.find('.' + initOption.itemClosestParentClass + ':first > div').toArray().sort(function (a, b) {
            //                 return FormLocal[$(a).find('[' + initOption.nameFlag + ']').attr(initOption.nameFlag)] - FormLocal[$(b).find('[' + initOption.nameFlag + ']').attr(initOption.nameFlag)]
            //             })
            //             var newrow = $('<div/>', { class: initOption.itemClosestParentClass }).append(newform)
            //             if (!!FormLocal['hide']) {
            //                 $.each(FormLocal['hide'], function (i, item) {
            //                     newrow.find('[' + initOption.nameFlag + '="' + item + '"]').closest(initOption.itemClosest).addClass('layui-hide')
            //                 })
            //                 newrow.find('.layui-hide [' + initOption.nameFlag + ']').each(function () {
            //                     if (FormLocal['hide'].indexOf($(this).attr(initOption.nameFlag)) == -1) {
            //                         $(this).closest(initOption.itemClosest).removeClass('layui-hide')
            //                     }
            //                 })
            //             }
            //             $form.find('.' + initOption.itemClosestParentClass + ':first').replaceWith(newrow)
            //         },
            //         error: function () {
            //             timemsg.open('下载个性化设置失败！')
            //         }
            //     })
            // }
            //清除本地缓存
            // layui.active.clearFormLocal = function () {
            //     var $form = return$Form($(this))
            //     var filter = $form.attr('formClass') || $form.attr('lay-filter')
            //     localStorage.removeItem(location.pathname + ':' + filter)
            //     timemsg.open('清除个性化设置成功！')
            // }
            //筛选显示控件
            layui.active.filterItem = function (obj) {
                var $this = $(this)
                if ($(obj[0].target).hasClass('header-btn-panel') || $(obj[0].target).closest('.header-btn-panel').length > 0 || $this.hasClass('active')) { return; }
                $this.addClass('active')

                var $form = return$Form($(this))
                var filter = $form.attr('formClass') || $form.attr('lay-filter')
                    //var LocalHide = formLocal[filter]['hide']
                    var LocalHide = null
                $panel = $('<ul/>', { class: 'header-btn-panel filter-panel' })

                //如果没保存过隐藏项
                // formLocal[filter]['hide'] || (formLocal[filter]['hide'] = [])
                formLocal[filter] = {}
                formLocal[filter]['hide'] = []

                $form.find('.' + initOption.itemClosestParentClass + ':first > div').each(function () {
                    if ($(this).hasClass('my-hide')) { return; }
                    if ($(this).hasClass('noShow')) { return; } // 表示在页面中显示，但是在筛选中不显示
                    var checked = 'checked', $item = $(this).find('[' + initOption.nameFlag + ']')
                    if ($(this).hasClass('layui-hide')) {
                        checked = false
                        if (!LocalHide) {
                            formLocal[filter]['hide'].push($item.attr(initOption.nameFlag))
                        }
                    }
                    $('<li><input type="checkbox" name="' + $item.attr(initOption.nameFlag) + '" lay-skin="primary" title="' + $(this).find('label').text() + '" lay-filter="filterItem" ' + (checked || '') + '></li>').appendTo($panel)
                })
                if ($this.attr('type') != 'button') {
                    //在隐藏面板点击进行偏移
                    $panel.css('right', $this.outerWidth(true) + 'px')
                }
                $panel.appendTo($this)
                form.render('checkbox')
                var istabsbody = $(frameElement).parent().hasClass('layadmin-tabsbody-item')
                if (!istabsbody && frameElement) {
                    window.frameElement.style['min-height'] = $panel.offset().top + $panel.outerHeight(true) + 'px'    //更新iframe高度
                }
                $(document).on('mousedown', function (e) {
                    setTimeout(function () {
                        //if ($(e.target).hasClass('header-btn-panel') || $(e.target).closest('.header-btn-panel').length > 0) { return; }
                        if ($(e.target).attr('data-type') == 'filterItem' || $(e.target).closest('[data-type="filterItem"]').length > 0) { return; }
                        $('.header-btn-panel').remove()
                        $this.removeClass('active')
                        if (!istabsbody) {
                            window.frameElement.style['min-height'] = '0px'
                        }
                        $(document).unbind(e)
                    }, 100)
                })
            }

            //筛选显示 checkbox
            form.on('checkbox(filterItem)', function (obj) {
                var $form = return$Form($(this))
                var filter = $form.attr('formClass') || $form.attr('lay-filter'),
                    thisName = this.name
                $item = $form.find('[' + initOption.nameFlag + '="' + thisName + '"]').closest(initOption.itemClosest)
                if (this.checked) {
                    $item.removeClass('layui-hide')
                    formLocal[filter]['hide'].remove(thisName)
                } else {
                    $item.addClass('layui-hide')
                    formLocal[filter]['hide'].push2(thisName)
                }
                if (!!layui.enterTab) {
                    layui.enterTab.$inputs = $form.find(layui.enterTab.jqSelector); // 更新表单中的所有可用输入框，用于更新enterTab
                }
                localStorage.setItem(location.pathname + ':' + filter, deepStringify(formLocal[filter]))  //保存本地
            })

            // setArrRemove()  //数组用内容移除某项 remove, 可多项
            // setArrpush2()   //给数组原型添加非重复插入方法 push2, 可多项

            //上传默认值
            // layui.active.upAccountDefault = function () {
            //     var $form = return$Form($(this))
            //     var filter = $form.attr('lay-filter'), billType = location.pathname + ':' + filter
            //     AccountDefaultSave(filter, billType, layui)
            // }


            function return$Form($this) {
                // 获取$form
                var $form,
                    $tabCard = $this.closest('.forceForm-tabCard'),
                    $collaCard = $this.closest('.forceForm-collaCard');
                if ($tabCard.length > 0 && $collaCard.length === 0) {
                    var $checkElem = $tabCard.find(':not(.forceForm-card) [name="forceFormCheck"]:checked').eq(0)
                    $form = $checkElem.closest('.forceForm-item').find('form')
                } else if ($collaCard.length > 0 && $tabCard.length === 0) {
                    var $checkElem = $collaCard.find(':not(.forceForm-card) [name="forceFormCheck"]:first')
                    $form = $checkElem.closest('.forceForm-item').find('form')
                } else {
                    $form = $this.closest('.layui-card-header').siblings('.layui-card-body').find('form')
                }

                return $form
            }
        },
        formView: function (data, active, select2open) {
            /**
             * 方法说明 form循环
             * @param {obj} data 需要循环的数据
             * @param {obj} active Form Header 按钮运行代码存在页面内引用
             * @param {obj} select2open select2 定义函数
             */
            var _this = this
            var $formCard = $('.tab_form_card:first')
            if ($formCard.length == 0) { return; }
            if (!data || data.total == 0) {
                //没有数据时显示‘无数据’
                $('.header_btn').closest('.layui-card.layui-hide').removeClass('layui-hide')
                return;
            }
            $.each(data.rows, function (i, item) {
                var $formCardc = $formCard.clone(), $formc = $formCardc.find('form')
                $formc.attr('lay-filter', 'form-body' + i + '')
                $formc.attr('formClass', 'form-body')
                $formCardc.find('.layui-card-header > text').text(item.Guid)
                $formCardc.removeClass('layui-hide')
                $formCardc.appendTo($formCard.parent())

                ;!select2open || select2open(item, $formc)   //form 循环标签不能有id，否则select2自身将错误渲染
                var formData = form.val("form-body" + i + "", item)
                !!formData.Guid || formVal1("form-body" + i, item)  //防止原生 form 赋值无效
            })
            $formCard.find('form').addClass('layui-hide')   //给 form 添加 layui-hide Class,便于 enterTab 识别
            if (!!data.fun) {
                data.fun()  //存在完成事件则执行
            }
            layuiDateload()
            form.render()
            iframe_height()
            _this.custom(active)
            if (data.total != 0 && data.total <= 2) {
                select2Height() //防止页内高度不够select2显示
                laydateHeight() //防止页内高度不够lay-date显示
            }
            $('.tab_form_card .layui-card-header > :not(.header-btn-group)').on('click', function () {
                //选中事件
                var $checkboxDiv = $(this).siblings('.layui-form-checkbox')
                $checkboxDiv.toggleClass('layui-form-checked')
                var $checkbox = $(this).siblings('[data-type]')
                if ($checkbox.length == 0) { return; }
                var type = $checkbox.data('type');
                active[type] ? active[type].call($checkbox[0], $checkboxDiv.hasClass('layui-form-checked')) : '';
            });
        },
        collaFormView: function (data, active, select2open, options) {
            /**
             * 方法说明 form循环
             * @param {obj} data 需要循环的数据
             * @param {obj} active Form Header 按钮运行代码存在页面内引用
             * @param {obj} select2open select2 定义函数
             */
            !!options || (options = {})

            var _this = this
            var $collaCard = $('.forceForm-collaCard'),
                $formCard = $collaCard.find('.forceForm-item:first')
            if ($collaCard.length === 0 || $formCard.length == 0) { return; }
            if (!data || data.total == 0) {
                //没有数据时显示‘无数据’
                $('.header_btn').closest('.layui-card.layui-hide').removeClass('layui-hide')
                $collaCard.find('.header-btn-group .btn-option').hide()
                //return;
            }

            $collaCard.find('.header-btn-group').show()
            $collaCard.find('.layui-colla-title').css('position', 'static')     //筛选面板因 title position: relative 显示异常，此处需修改定位方式
            $.each(data.rows, function (i, item) {
                var $formCardc = $formCard.clone(), $formc = $formCardc.find('form')
                $formc.attr('lay-filter', 'form-body' + i + '')
                $formc.attr('formClass', 'form-body')
                $formCardc.find('.layui-card-header > text').text(item.Guid)
                $formCardc.removeClass('layui-hide')
                $formCardc.appendTo($formCard.parent())

                var $forceFormCheck = '';
                if (options.deleteBtn) {
                    $forceFormCheck = $(`<div class="forceFormCheck"><button name="forceFormCheck" type="button" class="layui-btn layui-btn-xs " style="background-color: #fff; color: #000;"> 
                    <i class="layui-icon layui-icon-delete" style=" margin: 0;font-size: 18px !important;"></i> </button></div>`)
                    $formCardc.append($forceFormCheck)
                } else {
                    $forceFormCheck = $('<div class="forceFormCheck"><input type="checkbox" name="forceFormCheck" alt="选中当前form个性化" lay-skin="primary"></div>')
                    $formCardc.append($forceFormCheck)
                }
                /*if (i === 0) {
                    $forceFormCheck[0].checked = true
                }*/

                ; !select2open || select2open(item, $formc)   //form 循环标签不能有id，否则select2自身将错误渲染
                var formData = form.val("form-body" + i + "", item)
                !!formData.Guid || formVal1("form-body" + i, item)  //防止原生 form 赋值无效
            })
            $formCard.find('form').remove()     //移除 form 留下空 .forceForm-item
            if (!!data.fun) {
                data.fun()  //存在完成事件则执行
            }
            layuiDateload()
            form.render()
            if (options.deleteBtn) {
                $collaCard.find(".forceFormCheck .layui-unselect.layui-form-checkbox").addClass("my-hide");
                $(".forceFormCheck").on("click", ".layui-btn.layui-btn-xs", active, function (event) {
                    event.data.delete2.call(this, arguments)
                });
                $(".forceFormCheck").on("mousemove", ".layui-btn.layui-btn-xs", function () {
                    $(this).css({
                        "color": "#fff",
                        "background-color": "#FF5722"
                    });
                });
                $(".forceFormCheck").on("mouseout", ".layui-btn.layui-btn-xs", function () {
                    $(this).css({
                        "background-color": "#fff",
                        "color": "#000"
                    });
                });
            }
            iframe_height(options.isIframeSon)
            _this.custom(active, {
                isCollaFormView: true,
                headerRWSelector: ['> span']
            })
            if (data.total != 0 && data.total <= 3) {
                select2Height() //防止页内高度不够select2显示
                laydateHeight() //防止页内高度不够lay-date显示
            }
        },
        tabFormView: function (data, options) {
            /**
             * 方法说明：tab form循环
             * @param {obj} data 需要循环的数据
             * @param {obj} active Form Header 按钮运行代码存在页面内引用
             * @param {obj} select2open select2 定义函数
            */
            !!options || (options = {})

            var _this = this

            var $tabCard = $('.forceForm-tabCard'),
                $tabTitle = $tabCard.find('.layui-tab-title li:first'),
                $tabContent = $tabCard.find('.layui-tab-content .layui-tab-item:first')

            if ($tabCard.length === 0 || $tabContent.length === 0) { return; }
            if (!data || data.total == 0) {
                //没有数据时显示‘无数据’
                var $header_btnCard = $('.header_btn').closest('.layui-card.layui-hide')
                $tabCard.after($header_btnCard)
                $tabCard.find('.layui-tab-content').hide()
                $header_btnCard.removeClass('layui-hide')
                $tabCard.find('.header-btn-group .btn-option').hide()
                //return;
            }

            $tabCard.find('.header-btn-group').show()
            $.each(data.rows, function (i, item) {
                var $tabTitleC = $tabTitle.clone(true),
                    $tabContentC = $tabContent.clone(true),
                    $formc = $tabContentC.find('form')
                $formc.attr('lay-filter', 'form-body' + i + '')
                $formc.attr('formClass', 'form-body')

                !options.tabTItemKey || $tabTitleC.text(item[options.tabTItemKey])    //tab 名称
                $tabContentC.removeClass('layui-hide')

                var $forceFormCheck = $('<div class="forceFormCheck"><input type="checkbox" class="layui-hide" name="forceFormCheck" title="选中当前form个性化" lay-skin="primary" lay-ignore></div>')
                $tabContentC.append($forceFormCheck)

                !options.forFun || options.forFun(i, item, $tabTitleC, $tabContentC)

                if (i === 0) {
                    $tabTitleC.addClass('layui-this')
                    $tabContentC.addClass('layui-show')
                    $forceFormCheck.find('[name="forceFormCheck"]')[0].checked = true
                }
                $tabCard.find('.layui-tab-title').append($tabTitleC)
                $tabCard.find('.layui-tab-content').append($tabContentC)

                !options.select2open || options.select2open(item, $formc)   //form 循环标签不能有id，否则select2自身将错误渲染
                var formData = form.val("form-body" + i + "", item)
                !!formData.Guid || formVal1("form-body" + i, item)  //防止原生 form 赋值无效
            })
            $tabTitle.remove()
            $tabContent.remove()

            element.on('tab(forceForm-tabCard)', function (data) {
                //监听 tab 切换
                iframe_height()
                var $forceFormCheck = $tabCard.find(':not(.forceForm-card) [name="forceFormCheck"]')
                $forceFormCheck.prop('checked', false)
                $forceFormCheck.eq(data.index).prop('checked', true)

                $tabCard.find('.layui-tab-item').each(function (key, item) {
                    $(this).find('form .layui-form-label').css('cursor', 'default').off('mousedown')
                })

                $FormCustom = $tabCard.find('[data-type="FormCustom"]')
                if ($FormCustom.hasClass('active')) {
                    layui.active.FormCustom.call($FormCustom[0])
                }
            });

            $tabContent.find('form').addClass('layui-hide')   //给 form 添加 layui-hide Class,便于 enterTab 识别
            ;!options.fun || options.fun()  //存在完成事件则执行
                
            layuiDateload()
            form.render()
            iframe_height()
            _this.custom(options.active, {
                isTabFormView: true,
                headerRWSelector: ['> li']
            })
            if (data.total == 1) {
                select2Height() //防止页内高度不够select2显示
                laydateHeight() //防止页内高度不够lay-date显示
            }
        }
    };
    //输出接口
    exports('forceForm', obj);
});